package com.phx.uart;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialPort {

    private static final String TAG = "SerialPort";
    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    public SerialPort(String device, int baudrate) throws SecurityException, IOException {
      //  mFd = open(device.getAbsolutePath(), baudrate);
        mFd = open(device, baudrate);
        if (mFd == null) {
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    private native FileDescriptor open(String path, int baudrate);
    public native int close();

//    static {
//        System.loadLibrary("uart_phx");
//    }

//    //从串口对象中获取输出流
//    OutputStream outputStream = serialPort.getOutputStream();
//    //需要写入的数据
//    byte[] data = new byte[x];
//    data[0] = ...;
//    data[1] = ...;
//    data[x] = ...;
////写入数据
//outputStream.write(data);
//outputStream.flush();
//从串口对象中获取输入流
//InputStream inputStream = serialPort.getInputStream();
////使用循环读取数据，建议放到子线程去
//while (true) {
//        if (inputStream.available() > 0) {
//            //当接收到数据时，sleep 500毫秒（sleep时间自己把握）
//            Thread.sleep(500);
//            //sleep过后，再读取数据，基本上都是完整的数据
//            byte[] buffer = new byte[inputStream.available()];
//            int size = inputStream.read(buffer);
//        }
//    }
}